﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.LocalMachine.BotCommands;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace Netfraction.Hub.Bots.AnnouncerBot.Handlers
{
    [CommandHandler("listreleases")]
    public class ListReleases : CommandHandler
    {
        public override bool HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            string lastXReleases = "-1";
            if (message.UnnamedArguments.Count == 1)
            {
                int numReleases;
                if (int.TryParse(message.UnnamedArguments[0], out numReleases))
                {
                    lastXReleases = message.UnnamedArguments[0];
                }
            }


            Community.CsharpSqlite.SQLiteClient.SqliteDataReader sdr = AnnouncerBot.DataStore.ExecuteQuery("SELECT Users.Username AS AddedBy, Date, Time, Categories.Name AS Category, Magnet FROM Entries JOIN Users ON Entries.AddedBy=Users.UserId JOIN Categories ON Entries.CategoryId=Categories.CategoryId ORDER BY Entries.Date DESC, Entries.Time DESC LIMIT " + lastXReleases);
            if (sdr != null)
            {
                string user, date, time, category, magnet;
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("All releases in the database (<Added By> [Time Added] [Category] - Magnet Link)");
                sb.AppendLine("Use '!listreleases x' to show the last x releases, or '!help listreleases' for more information.");
                int i = 1;
                while (sdr.Read())
                {
                    user = sdr.GetString(0);
                    date = sdr.GetString(1);
                    time = sdr.GetString(2);
                    category = sdr.IsDBNull(3) ? "N/A" : sdr.GetString(3);
                    magnet = sdr.GetString(4);

                    sb.AppendLine(String.Format("{0}: <{1}> [{2} - {3}] [{4}] - Magnet Link: {5}", i, user, date, time, category, magnet));

                    i++;
                }
                this.ParentBot.SendEchoMessageFromBot(source, sb.ToString());
            }

            return true;
        }
    }
}
